﻿using AutoMapper;
using Newtonsoft.Json;
using Ross.EntityFramework;
using Ross.EntityFramework.Model;
using Ross.Service.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Ross.Service
{
  public  class BuMenService: BaseService, IDisposable
    {
        private TranDbContext dbContext;
        public IRepository<Targets, int> repository;
        public IRepository<Users, int> userresp;
        /// <summary>
        /// 默认版本号
        /// </summary>
        public BuMenService(string nameOrConnectionString)
        {
            dbContext = new TranDbContext(nameOrConnectionString);
            repository = new Repository<Targets, int>(dbContext);
            userresp = new Repository<Users, int>(dbContext);
        }
        public ResultDto<List<Dto.TargetOutput>> GetTreeList(string keywords = "", string departId = "", string status = "", string timespan="")
        {
            List<Dto.TargetOutput> trees = new List<TargetOutput>();
            ResultDto<List<Dto.TargetOutput>> result = new ResultDto<List<Dto.TargetOutput>>();
            var listsAll = repository.GetAllList();
            if (!string.IsNullOrEmpty(username))
            {
                var user = userresp.GetAllList(o => o.UserName == username || o.EmpID == username).FirstOrDefault();
                string[] adepts = user.AuthorizedDepartment.Split(',');
                var root = repository.GetAllList(o => o.Depth == 0 && o.TargetName == year.ToString()).ToList();
                List<Targets> targets = new List<Targets>();
                targets = GetTargetsData(root[0], targets);
                targets = targets.Where(t => t.Depth == 3 && t.Lock == true).ToList();
                if (!string.IsNullOrEmpty(keywords))
                    targets = targets.Where(t => t.TargetName.Contains(keywords)).ToList();
                if (!string.IsNullOrEmpty(departId))
                    targets = targets.Where(t => t.Department == departId).ToList();
                else
                    targets = targets.Where(t => adepts.Contains(t.Department)).ToList();
                if (!string.IsNullOrEmpty(status))
                    targets = targets.Where(t => t.ApprovalStatus == status).ToList();
                if (!string.IsNullOrEmpty(timespan))
                {
                    DateTime starttime = Convert.ToDateTime(timespan.Split(',')[0]);
                    DateTime endtime = Convert.ToDateTime(timespan.Split(',')[1]);
                    targets = targets.Where(t => t.StartingTime >= starttime && t.StartingTime <= endtime).ToList();
                }
                foreach (var item in targets)
                {
                    TargetOutput obj = new TargetOutput();
                    obj = Mapper.Map<Dto.TargetOutput>(item);
                    obj.children = GetTargetsTree(listsAll, item.ID);
                    if (obj.children.Count == 0)
                        obj.children = null;
                    trees.Add(obj);
                }
                #region
                //foreach (var item in trees)
                //{
                //    var ls = repository.GetAllList(o => o.ID == item.ParentTargetID).FirstOrDefault();//tree 的-1
                //    if (zhanlue.Count > 0)
                //    {
                //        int id = ls.ID;
                //        var rs = zhanlue.Where(o => o.ID == id).ToList();
                //        if (rs.Count > 0)
                //        {
                //            for (int i = 0; i < zhanlue.Count; i++)
                //            {
                //                if (zhanlue[i].ID == ls.ID)
                //                {
                //                    //zhanlue[i].children = new List<TargetOutput>();
                //                    zhanlue[i].children.Add(item);
                //                }
                //            }
                //        }
                //        else
                //        {
                //            var obj = Mapper.Map<Dto.TargetOutput>(ls);
                //            obj.children = new List<TargetOutput>();
                //            obj.children.Add(item);
                //            zhanlue.Add(obj);
                //        }
                //    }
                //    else
                //    {
                //        var obj = Mapper.Map<Dto.TargetOutput>(ls);
                //        obj.children = new List<TargetOutput>();
                //        obj.children.Add(item);
                //        zhanlue.Add(obj);
                //    }
                //}
                #endregion
            }
            result.total = trees.Count;
            result.datas = trees;
            return result;
        }
        /// <summary>
        /// 返回登录年份所有的数据
        /// </summary>
        /// <returns></returns>
        List<Targets> GetTargetsData(Targets targets,List<Targets> list)
        {
            var t = repository.GetAllList(o => o.ParentTargetID == targets.ID).ToList();
            if (t.Count > 0)
            {
                foreach (var item in t)
                {
                    list.Add(item);
                    GetTargetsData(item, list);
                }

            }
            return list;
        }

        private List<Dto.TargetOutput> GetTargetsTree(List<Targets> datas, int parentid = -1)
        {
            List<Dto.TargetOutput> result = new List<Dto.TargetOutput>();
            var lists = datas.Where(o => o.ParentTargetID == parentid).ToList();
            foreach (var item in lists)
            {
                Dto.TargetOutput obj = new Dto.TargetOutput();
                obj = Mapper.Map<Dto.TargetOutput>(item);
                var childrens = datas.Where(o => o.ParentTargetID == item.ID).ToList();
                if (childrens.Count > 0)
                {
                    obj.children = GetTargetsTree(datas, item.ID);
                }
                result.Add(obj);
            }
            return result;
        }
        /// <summary>
        /// 部门目标树
        /// </summary>
        /// <param name="bumenmingcheng">默认自己部门，也可根据权限选择</param>
        /// <param name="starttime">开始时间</param>
        /// <param name="endtime">结束时间</param>
        /// <param name="mubiao">部门目标</param>
        /// <param name="zhuangtai">审批状态</param>
        /// <returns></returns>
        //public ResultDto<List<Dto.TargetOutput>> ChaXunBuMen(string bumenmingcheng, string [] timespan, string mubiao = "", string zhuangtai = "")
        //{
        //    var result = new ResultDto<List<Dto.TargetOutput>>();
        //    List<Dto.TargetOutput> list = new List<TargetOutput>();
        //    var datas = new ResultDto<List<Dto.TargetOutput>>();
        //    List<Dto.TargetOutput> set = null;
        //    datas = GetTreeList();
        //    foreach (var tree in datas.datas)
        //    {
        //        foreach (var bumen in tree.children)
        //        {
        //            if (Exist(set, bumen, bumenmingcheng, timespan, mubiao, zhuangtai))
        //            {
        //                list.Add(tree);
        //                break;
        //            }
        //            else
        //            {
        //                foreach (var child1 in bumen.children)
        //                {
        //                    if (Exist(set, child1, bumenmingcheng, timespan, mubiao, zhuangtai))
        //                    {
        //                        list.Add(tree);
        //                        break;
        //                    } 
        //                    else
        //                    {
        //                        foreach (var child2 in child1.children)
        //                        {
        //                            if (Exist(set, child2, bumenmingcheng, timespan, mubiao, zhuangtai))
        //                            {
        //                                list.Add(tree);
        //                                break;
        //                            }
        //                            else
        //                            {
        //                                foreach (var child3 in child2.children)
        //                                {
        //                                    if (Exist(set, child3, bumenmingcheng, timespan, mubiao, zhuangtai))
        //                                    {
        //                                        list.Add(tree);
        //                                        break;
        //                                    }
        //                                }
        //                            }
        //                        }
        //                    }
        //                }
        //            }
        //        }
        //    }
        //    result.datas = list;
        //    return result;
        //    //
        //} 

        //bool Exist(List<Dto.BuMenBiaoOutput> set, BuMenBiaoOutput bumen, string bumenmingcheng,string[] timespan, string mubiao = "", string zhuangtai = "")
        //{
        //    DateTime starttime = Convert.ToDateTime(timespan[0]);
        //    DateTime endtime = Convert.ToDateTime(timespan[1]);
        //    set = new List<Dto.BuMenBiaoOutput>();
        //    set.Add(bumen);
        //    set = set.Where(t => t.Department == bumenmingcheng & (t.StartingTime >=starttime & t.StartingTime<= endtime)).ToList();
        //    if (!string.IsNullOrEmpty(mubiao))
        //        set = set.Where(t => t.TargetName.Contains(mubiao) == true).ToList();
        //    if (!string.IsNullOrEmpty(zhuangtai))
        //        set = set.Where(t => t.ApprovalStatus == zhuangtai).ToList();
        //    if (set.Count > 0)
        //        return true;
        //    else
        //        return false;
        //}

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            dbContext.Dispose();
        }
    }
}
